package com.aliang.shopping.util.excel;


import com.aliang.shopping.contact.ExcelConstant;
import com.aliang.shopping.util.excel.listener.MyAnalysisEventListener;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * Excel 工具类
 */
@Component
public class ExcelUtils {

    public <T> String importExcel(InputStream is, Class clazz, MyAnalysisEventListener<T> listener) {
        EasyExcel.read(is, clazz, listener).sheet().doRead();
        return listener.getMsg();
    }


    /**
     * 设置请求头
     *
     * @param response
     * @param fileName
     * @throws UnsupportedEncodingException
     */
    public void setHeader(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        //向外部暴露请求头
        response.setHeader(ExcelConstant.ACCESS_CONTROL_EXPOSE_HEADERS, ExcelConstant.CONTENT_DISPOSITION);
        response.setContentType(ExcelConstant.CONTENT_TYPE_VALUE);
        response.setHeader(ExcelConstant.CONTENT_DISPOSITION, ExcelConstant.CONTENT_DISPOSITION_VALUE + URLEncoder.encode(fileName, String.valueOf(StandardCharsets.UTF_8)));
    }


    public void downloadTemplate(HttpServletResponse response, String fileName) throws IOException {
        //设置请求头
        setHeader(response, fileName);
        //获取文件输入流
        String fileClassPath = "templates" + File.separator + "excel" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);
        //通过输出流向前端返回数据
        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
        excelWriter.finish();
    }
}
